package com.qingcheng.service.impl;

import com.qingcheng.util.CacheKey;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.PreferentialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private SkuService skuService;

    @Reference
    private CategoryService categoryService;


    /**
     * 从Redis中获取购物车信息
     * @param username
     * @return
     */
    @Override
    public List<Map<String, Object>> findCartList(String username) {
        System.out.println("从Redis中获取购物车信息,用户名："+username);
        //利用枚举类型
        List<Map<String,Object>> cartLsit = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        //如果获取的cartList购物车集合为空，则将其实例化为一个空的集合示例
        if (cartLsit==null){
            cartLsit=new ArrayList<>();
        }

        return cartLsit;
    }

    /**
     * 添加商品到购物车
     * @param username 用户名
     * @param skuId    商品规格Id
     * @param num       商品数量
     */
    @Override
    public void addItem(String username, String skuId, Integer num) {
        //遍历商品购物车，如果购物车存在该商品则更新商品数量，如果没有该商品则添加该商品到购物车
        //获取购物车信息
        /**
         * Map类型：
         *      item: OrderItem类型，购物车明细
         *      checked：布尔类型，表示是否选中
         */
        List<Map<String, Object>> cartList = findCartList(username);
        boolean flag = false;//判断在购物车中是否存在该商品
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (orderItem.getSkuId().equals(skuId)){//购物车已存在该商品，
                if (orderItem.getNum()<=0){//商品数量小于等于0，则移除购物车
                    cartList.remove(map);
                    break;
                }
                int weight = orderItem.getWeight()/orderItem.getNum();//单个商品重量
                orderItem.setNum( orderItem.getNum()+ num);//数量变更
                orderItem.setWeight(weight*orderItem.getNum());
                orderItem.setMoney(orderItem.getPrice()*orderItem.getNum());

                if (orderItem.getNum()<=0){
                    cartList.remove(map);//购物车删除商品
                }

                flag=true;
                break;
            }
        }

        //购物车不存在商品时
        if (flag == false){
            Sku sku = skuService.findById(skuId);
            if (sku==null){
                throw new RuntimeException("商品不存在");
            }
            if (!"1".equals(sku.getStatus())){
                throw new RuntimeException("商品状态不合法");
            }
            if (num<0){//商品数量不能为0，
                throw new RuntimeException("商品数量不合法");
            }

            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(skuId);
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(num);
            orderItem.setImage(sku.getImage());
            orderItem.setName(sku.getName());
            if (sku.getWeight()==null){
                sku.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight()*num);
            orderItem.setPrice(sku.getPrice());
            orderItem.setMoney(sku.getPrice()*num);

            //商品分类
            orderItem.setCategoryId3(sku.getCategoryId());
            //根据三级分类Id查找二级分类Id,   sku.getCategoryId()指当前商品的Id，及三级id
            /**
             * 进行多次查询，性能较差，可进行缓存查询，先将分类存到缓存中，在进行缓存查询
             */
//            Category category3 = categoryService.findById(sku.getCategoryId());
//            orderItem.setCategoryId2(category3.getParentId());
//            Category category2 = categoryService.findById(category3.getParentId());
//            orderItem.setCategoryId1(category2.getParentId());

            Category category3 =(Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(sku.getCategoryId());
            if (category3==null){
                //如果为null，即尚未存到缓存中，进行缓存存储
                category3 = categoryService.findById(sku.getCategoryId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(sku.getCategoryId(),category3);
            }
            orderItem.setCategoryId2(category3.getParentId());

            Category category2 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(category3.getParentId());
            if (category2==null){//缓存中没有
                category2 = categoryService.findById(category3.getParentId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category3.getParentId(),category2);
            }
            orderItem.setCategoryId1(category2.getParentId());

            Map map = new HashMap();
            map.put("item",orderItem);
            map.put("checked",true);

            cartList.add(map);
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);


    }

    /**
     * 更新选中状态
     * @param username
     * @param skuId
     * @param checked
     * @return
     */
    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        //获取购物车信息
        List<Map<String, Object>> cartList = findCartList(username);
        boolean isOk = false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (orderItem.getSkuId().equals(skuId)){
                map.put("checked",checked);
                isOk=true;
                break;
            }
        }
        //如果更新数据则存入缓存
        if (isOk){
            redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
        }
        return isOk;
    }

    /**
     *
     * @param username
     */
    @Override
    public void deleteCheckedCart(String username) {
//        List<Map<String, Object>> cartList = findCartList(username);
//        for (Map<String, Object> map : cartList) {
//            boolean checked = (boolean)map.get("checked");
//            if (checked){
//                cartList.remove(map);
//                redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
//            }
//        }

        //使用lambda表达式：过滤掉checked==false的商品信息
        List<Map<String, Object>> cartList = findCartList(username).stream()
                .filter(cart -> (boolean) cart.get("checked") == false)
                .collect(Collectors.toList());

        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);



    }



    @Autowired
    private PreferentialService preferentialService;
    /**
     * 计算当前选中的优惠金额
     * @param username
     * @return
     */
    @Override
    public int preferential(String username) {
        //获取购物车信息，查找checked==true的商品，获取List<OrderItem>，计算优惠金额
        List<OrderItem> orderItemList = findCartList(username).stream()
                .filter((cart -> (boolean) cart.get("checked") == true))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());

        //按照分类聚合计算各分类商品的优惠金额
        //分类   优惠金额
        //  1       20  40
        //  2       30
        Map<Integer, IntSummaryStatistics> cartMap = orderItemList.stream()
                .collect(Collectors.groupingBy(OrderItem::getCategoryId3,
                        Collectors.summarizingInt(OrderItem::getMoney)));
        //Collectors.summarizingInt----聚合统计方法

        //循环遍历并累加优惠金额
        int allPreMoney=0;
        for (Integer categoryId : cartMap.keySet()) {
            int money =(int) cartMap.get(categoryId).getSum();
            int preMoney = preferentialService.findPreMoneyByCategoryId(categoryId, money);

            allPreMoney+=preMoney;
            System.out.println("分类："+categoryId+"消费金额："+money+"优惠金额："+preMoney);
        }
        return allPreMoney;
    }

    /**
     * 获取更新商品价格
     * @param username 用户名
     * @return
     */
    @Override
    public List<Map<String, Object>> findNewOrderItemList(String username) {
        List<Map<String, Object>> cartList = findCartList(username);
        //cart:  "item":{}
        //    "checked":--
        for (Map<String, Object> cart : cartList) {
            OrderItem orderItem = (OrderItem) cart.get("item");
            String skuId = orderItem.getSkuId();
            Sku sku = skuService.findById(skuId);
            //获取数据库商品价格并更新到缓存OrderItem中
            orderItem.setPrice(sku.getPrice());//更新价格
            orderItem.setMoney(orderItem.getPrice()*orderItem.getNum());//更新金额

        }

        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);

        return cartList;
    }
}
